import jsBridge from "./jsBridge"
/**
 * 打开新的webview
 * @param {String} url 
 */
export const openPage = (url) => {
  console.log('打开新webview')
  jsBridge.callHandler('openPage', {
    url
  });
}
/**
 * 打开登录页
 */
export const login = () => {
  console.log('打开登录页')
  jsBridge.callHandler('login');
}
/**
 * 刷新token
 * @param {String} token 
 */
export const refreshToken = (token) => {
  console.log('刷新token')
  jsBridge.callHandler('refreshToken', {
    token
  })
}
/**
 * 关闭webview
 */
export const closePage = () => {
  console.log('关闭webview')
  jsBridge.callHandler('closePage')
}
/**
 * 拨打电话
 * @param {String} phone 
 */
export const callPhone = (phone) => {
  console.log('拨打电话')
  jsBridge.callHandler('callPhone', {
    phone
  });
}
/**
 * 调起支付
 * @param {Number} payType 0:微信,1:支付宝
 * @param {String|Number} orderID 订单号
 */
export const pay = (payType, orderID) => {
  console.log('调起支付')
  return new Promise((resolve) => {
    jsBridge.callHandler('pay', {
      payType,
      orderID
    }, (jsonString) => {
      let jsonObject = JSON.parse(jsonString) || {};
      for (const key in jsonObject) {
        if (Object.prototype.hasOwnProperty.call(jsonObject, key)) {
          jsonObject[key] = decodeURIComponent(jsonObject[key]);
        }
      }
      resolve(jsonObject);
    });
  })
}
/**
 * 获取原生APP存储的数据
 * @param {String} type 需要获取的数据类型,如 token
 */
export const getAppDatas = (type) => {
  return new Promise(resolve => {
    jsBridge.callHandler('getAppDatas', {
      type
    }, (jsonString) => {
      let jsonObject = JSON.parse(jsonString) || {};
      for (const key in jsonObject) {
        if (Object.prototype.hasOwnProperty.call(jsonObject, key)) {
          jsonObject[key] = decodeURIComponent(jsonObject[key]);
        }
      }
      resolve(jsonObject);
    })
  })
}
